// pages/album/setting.js
import request from '../../utils/request'
import WxNotificationCenter from '../../utils/WxNotificationCenter'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    account: {},
    album: {},
    followers: [],
    hasChanged: false,
    isRemoving: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    this.setData({
      id: options.id,
      account: app.globalData.account,
    })
    // 获取相册基本信息
    this.fetchAlbum()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /*
   * 获取相册信息
   * 为了拿到群成员，需要通过接口获取album详情
   */
  fetchAlbum() {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id
    wx.showLoading({
      mask: true,
      title: '正在加载...',
    })
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      wx.hideLoading()
      if (!err) {
        that.setData({
          album: data
        })
      }
    })
  },

  /*
   * 点击踢人按钮
   */
  editFollowers: function (e) {
    if(this.data.album.follower.length < 2) {
      return wx.showModal({
        title: '提示',
        content: '相册只有您一个成员，去邀请好友加入吧！',
        showCancel: false
      })
    }
    let isRemoving = this.data.isRemoving
    this.setData({
      isRemoving: !isRemoving
    })
  },

  /*
   * 删除群成员
   */
  removeFollower : function (e) {
    let index = e.currentTarget.dataset.index
    let album = this.data.album
    let follower = album.follower[index]
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否确定将' + follower.nickname + '移除出相册?',
      success: function (res) {
        if (res.confirm) {
          let url = app.globalData.apiHost + '/albums/' + that.data.id + '/remove_follower/'
          let fd = { user_id: follower.id }
          wx.showLoading({
            title: '移除中...',
          })
          request(url, 'POST', app.globalData.loginToken, fd, function (err, data) {
            wx.hideLoading()
            if (!err) {
              album.follower.splice(index, 1)
              album.follower_count --
              that.setData({
                album: album
              })
              wx.showToast({
                title: '移除' + follower.nickname + '成功',
              })
              WxNotificationCenter.postNotificationName('removeFollower', { rnum: 1 })
            } else {
              wx.showToast({
                title: '移除' + follower.nickname + '失败',
              })
            }
          })
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let album = this.data.album
    let account = app.globalData.account
    let title = '【' + account.nickname + '】邀请您加入【' + album.title +'】'
    let imageUrl = album.icon
    return {
      title: title,
      path: '/pages/album/index?id=' + album.id +'&is_invite=true&share=true',
      imageUrl: imageUrl
    }
  },

  /*
   * 名字修改
   */
  nicknameChange: function (e) {
    let album = this.data.album
    album.baby_name = e.detail.value
    this.setData({
      album: album,
      hasChanged: true
    })
  },

  /*
   * 相册名字修改
   */
  albumNameChange: function (e) {
    let album = this.data.album
    album.title = e.detail.value
    this.setData({
      album: album,
      hasChanged: true
    })
  },

  /*
   * 相册名字修改
   */
  introChange: function (e) {
    let album = this.data.album
    album.intro = e.detail.value
    this.setData({
      album: album,
      hasChanged: true
    })
  },

  /*
   * 修改宝宝生日
   */
  bindDateChange: function (e) {
    let album = this.data.album
    album.baby_birthday = e.detail.value
    this.setData({ album: album, hasChanged: true })
  },

  /*
   * 选择宝宝性别
   */
  chooseGender: function () {
    let that = this
    let album = this.data.album
    wx.showActionSheet({
      itemList: ['未知', '小王子', '小公主'],
      success: function (res) {
        album.baby_gender = res.tapIndex
        that.setData({ album: album, hasChanged: true })
      }
    })
  },

  /*
   * 选择宝宝相册头像
   */
  chooseAvatar: function () {
    let account = app.globalData.account
    let album = this.data.album
    // 只有管理员可以点击操作
    if (account.id != album.sponsor.id) {
      return
    }
    let that = this
    wx.chooseImage({
      count: 1,
      sourceType: ['album'],
      sizeType: ['compressed'],
      success: function (res) {
        let formData = {}
        let url = app.globalData.apiHost + '/albums/' + album.id + '/upload_icon/'
        wx.showLoading({
          mask: true,
          title: '上传中...',
        })
        wx.uploadFile({
          url: url,
          filePath: res.tempFilePaths[0],
          name: 'icon',
          header: {
            'token': app.globalData.loginToken
          },
          formData: formData,
          success: function (res) {
            wx.hideLoading()
            if (res.statusCode >= 200 && res.statusCode < 300) {
              let data = JSON.parse(res.data)
              album.icon = data.icon
              that.setData({ album: album })
            }
          }
        })
      },
    })
  },

  /*
   * 更新信息
   */
  updateSetting: function() {
    if (!this.data.hasChanged) {
      return wx.showToast({
        title: '没有需要更新的信息',
        image: '/images/icon/icon_attention.png'
      })
    }
    let album = this.data.album
    // 验证数据完整性
    if (!album.baby_name) {
      return wx.showToast({
        title: '名字不能为空',
        image: '/images/icon/icon_attention.png'
      })
    }
    if (!album.baby_birthday) {
      return wx.showToast({
        title: '生日不能为空',
        image: '/images/icon/icon_attention.png'
      })
    }

    if (!album.title) {
      return wx.showToast({
        title: '相册名不能为空',
        image: '/images/icon/icon_attention.png'
      })
    }

    if (!album.intro) {
      return wx.showToast({
        title: '相册描述不能为空',
        image: '/images/icon/icon_attention.png'
      })
    }

    let that = this
    let url = app.globalData.apiHost + '/albums/' + album.id + '/'
    let formData = {
      baby_name: album.baby_name,
      baby_gender: album.baby_gender,
      baby_birthday: album.baby_birthday,
      title: album.title,
      intro: album.intro
    }
    wx.showLoading({
      mask: true,
      title: '正在更新...',
    })
    request(url, 'PUT', app.globalData.loginToken, formData, function (err, data) {
      console.log(data)
      wx.hideLoading()
      if (!err) {
        wx.showToast({
          title: '更新成功',
        })
      }
    })
    
  },

  /*
   * 退出相册
   */
  exitAlbum: function() {
    let that = this
    let album = this.data.album
    wx.showModal({
      title: '警告',
      content: '退出后只能通过邀请进入该相册，是否确定退出',
      success: function (res) {
        if (res.confirm) {
          let url = app.globalData.apiHost + '/albums/' + album.id + '/exit/'
          wx.showLoading({
            title: '正在退出...',
          })
          request(url, 'POST', app.globalData.loginToken, {}, function (err, data) {
            console.log(data)
            wx.hideLoading()
            if (!err) {
              wx.showToast({
                title: '退出成功',
              })
              WxNotificationCenter.postNotificationName('refreshAlbums')
              // 退出到首页
              wx.navigateBack({
                delta: 2
              })
            }
          })
        }
      }
    })
  }
})